"use strict"
const mvc = require('cosjs.mvc');
exports.format = {
    "id":'fbApp',
    "name":"facebook app(ACCESS服务器验证)",

    "verify": {
        "sandbox": "https://developers.facebook.com/docs/howtos/login/debugging-access-tokens",
        "production": "https://graph.facebook.com/debug_token",
    },

    "access":{
        "sandbox": "https://developers.facebook.com/docs/howtos/login/login-as-app",
        "production": "https://graph.facebook.com/oauth/access_token",
    },

    "fields":{
        "appid" :{'type':'string','val':'','name':"AppId"},
        "secret" :{'type':'string','val':'','name':"AppSecret"},
        "expire" :{'type':'int','val':0,'name':"access expire(天)"},
    }
};
//登录与认证TOKEN
exports.login = function () {
    let token = this.get("token","string");
    if(!token){
        return this.error("token empty");
    }
    let tokenKey = this.opensdk['_id'];
    let tokenModel = mvc.model.redis('token',this.branch);
    return tokenModel.get(tokenKey).then(ret=>{
        //console.log('tokenModel get',ret)
        if(ret){
            return ret;
        }
        //获取新的token
        return tokenModel.lock(tokenKey).then(ret=>{
            if(ret.length > 0){
                return this.error("tryAgain",5);
            }
            else {
                return get_facebook_access.call(this);
            }
        }).then(ret=>{
            return tokenModel.set(tokenKey,ret['access'],ret['expire']).then(ret=>ret['access'])
        })
    }).then(ret=>{
        let url = this.opensdk.status > 0 ? exports.format.verify.production : exports.format.verify.sandbox;
        let data = {"access_token":ret,"input_token":token}
        //console.log("request",url,JSON.stringify(data))
        return this.library("request/get",url,data,true);
    }).then(ret=>{
        //console.log("request ret",JSON.stringify(ret))
        if(!ret){
            return this.error('facebook_token_empty',ret);
        }
        if(ret['error']){
            return this.error(ret['error']['type'],ret['error']['message']);
        }
        if(!ret['data'] || !ret['data']["user_id"]){
            return  this.error("facebook_login_error",ret)
        }
        return  ret['data']["user_id"];
    })
};


exports.createOrder = function(config){
    return Promise.reject('closed')
}

//充值回调,sid|orderid
exports.orderNotify = function(){
    return Promise.reject('closed')
}
/**
 * @name orderResult
 * 包装游戏服发货信息
 */
exports.orderResult = function(err,ret){
    return Promise.reject('closed')
}



function get_facebook_access() {
    if(!this.opensdk.setting || !this.opensdk.setting.secret){
        return Promise.reject("opensdk.setting.secret empty");
    }
    let expire = this.opensdk.setting.expire ||1;
    let url = this.opensdk.status > 0 ? exports.format.access.production : exports.format.access.sandbox;
    let query = {"client_id":this.opensdk.setting.appid,"client_secret":this.opensdk.setting.secret,"grant_type":"client_credentials"}
    return this.library("request/get",url,query,true).then(ret=>{
        //console.log('get_facebook_access',ret)
        if(ret['error']){
            return Promise.reject({'err':"facebook",'ret':ret['error']});
        }
        else{
            return {"access":ret['access_token'],"expire":expire * 86400 };
        }
    })
}